﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Touch2Like.DAL;
using Touch2Like.Model;

namespace Touch2Like.Web.Admin.Popup
{
    public partial class AddMerchant : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                if (!string.IsNullOrEmpty(Request["ListID"]))
                {
                    Touch2Like.DAL.AuthorizedUserDAL user = new Touch2Like.DAL.AuthorizedUserDAL();
                    AuthorizedUserInfo info = user.GetByID(Convert.ToInt32(Request["ListID"]));

                    if (info != null)
                    {
                        tb_FirstName.Text = info.FirstName;
                        tb_LastName.Text = info.LastName;
                        tb_Email.Text = info.Email;
                    }
                }
            }
        }

        int GenerateCode()
        {
            Random rnd = new Random();
            int code = rnd.Next(10000000, 99999999);

            AuthorizedUserDAL user = new AuthorizedUserDAL();
            if (user.GetByRegistrationCode(code) == null)
            {
                return code;
            }
            else
            {
                return GenerateCode();
            }
        }

        protected void btn_Submit_Click(object sender, EventArgs e)
        {
            Touch2Like.DAL.AuthorizedUserDAL user = new Touch2Like.DAL.AuthorizedUserDAL();
            AuthorizedUserInfo info = new AuthorizedUserInfo();
            if (!string.IsNullOrEmpty(Request["ListID"]))
            {
                info = user.GetByID(Convert.ToInt32(Request["ListID"]));

                if (info == null) info = new AuthorizedUserInfo();
            }

            info.FirstName = tb_FirstName.Text;
            info.LastName = tb_LastName.Text;
            info.Email = tb_Email.Text;
            info.RegistrationCode = GenerateCode();

            AdminUserDAL admin = new AdminUserDAL();
            AdminUserInfo admininfo = admin.GetByUsername(WebUtility.AdminUsername);
            if (admininfo != null)
            {
                info.CreateUser = admininfo.AdminUserID;
            }

            if (!string.IsNullOrEmpty(Request["ListID"]))
            {
                info.ListID = Convert.ToInt32(Request["ListID"]);
                user.Update(info);
            }
            else
            {
                user.Add(info);
            }

            ClientScript.RegisterStartupScript(this.GetType(), "update", "<script>parent.document.location.href=parent.document.location.href;parent.document.location.reload();</script>");

        }
    }
}